//
// Created by castle on 2020/9/10.
//

#define CVUI_IMPLEMENTATION
#include "GameRender.h"
#include <string>

#define BUTTON_R_F ("./bits/r_f.png")
#define BUTTON_O_F ("./bits/o_f.png")
#define BUTTON_P_F ("./bits/p_f.png")
#define BUTTON_R_O ("./bits/r_o.png")
#define BUTTON_O_O ("./bits/o_o.png")
#define BUTTON_P_O ("./bits/p_o.png")
#define BUTTON_R_X ("./bits/r_x.png")
#define BUTTON_O_X ("./bits/o_x.png")
#define BUTTON_P_X ("./bits/p_x.png")

GameRender::GameRender(const char *windowTitle, int w, int h) : title(windowTitle)
{
	context = cv::Mat(cv::Size(w, h), CV_8UC3, backgroundColor);
	buttonImageSet[0][0] = cv::imread(BUTTON_R_F, cv::IMREAD_COLOR);
	buttonImageSet[0][1] = cv::imread(BUTTON_O_F, cv::IMREAD_COLOR);
	buttonImageSet[0][2] = cv::imread(BUTTON_P_F, cv::IMREAD_COLOR);
	buttonImageSet[1][0] = cv::imread(BUTTON_R_O, cv::IMREAD_COLOR);
	buttonImageSet[1][1] = cv::imread(BUTTON_O_O, cv::IMREAD_COLOR);
	buttonImageSet[1][2] = cv::imread(BUTTON_P_O, cv::IMREAD_COLOR);
	buttonImageSet[2][0] = cv::imread(BUTTON_R_X, cv::IMREAD_COLOR);
	buttonImageSet[2][1] = cv::imread(BUTTON_O_X, cv::IMREAD_COLOR);
	buttonImageSet[2][2] = cv::imread(BUTTON_P_X, cv::IMREAD_COLOR);
	cvui::init(windowTitle);
}

int GameRender::DrawCellsAndGetMouseEvent(const uint8_t *cells)
{
	int numPressed = -1;
	for(int i = 0; i < 3; ++i)
	{
		for(int j = 0; j < 3; ++j)
		{
			if(cvui::button(context,
							cellsXY[0] + j * cellOffset,
							cellsXY[1] + i * cellOffset,
							buttonImageSet[cells[i*3+j]][0],
							buttonImageSet[cells[i*3+j]][1],
							buttonImageSet[cells[i*3+j]][2]))
			{
				numPressed = i*3+j;
			}
		}
	}
	return numPressed;
}

void GameRender::DrawInfo(GameLogic::GameStatue statue, uint8_t player)
{
	std::string hintInfo;
	std::string resultInfo;
	const static std::string exitInfo = "Press Esc to exit the game.";

	switch(statue)
	{
		case GameLogic::GameStatue::Playing :
			char str[100];
			sprintf(str, "Player%d, Select a target!", player);
			hintInfo = str;
			cvui::text(context, 40, 40, hintInfo, 0.45, 0xff0000);
			break;
		case GameLogic::GameStatue::Player1Win :
			resultInfo = "Player1 win!";
			cvui::text(context, 40, 40, resultInfo, 0.45, 0x00ff00);
			break;
		case GameLogic::GameStatue::Player2Win :
			resultInfo = "Player2 win!";
			cvui::text(context, 40, 40, resultInfo, 0.45, 0x00ff00);
			break;
		case GameLogic::GameStatue::Draw :
			resultInfo = "Draw!";
			cvui::text(context, 40, 40, resultInfo, 0.45, 0x00ff00);
			break;
		default :
			break;
	}

	cvui::text(context, 40, 60, exitInfo, 0.45, 0x00ffff);
}
